<template>
  <div class="log">
    <basic-container>
      <avue-crud
          ref="crud"
          :data="tableData"
          :option="tableOption"
          :page.sync="page"
          :permission="permissionList"
          :table-loading="tableLoading"
          @on-load="getList"
          @search-reset="searchReset"
          @search-change="searchChange"
          @refresh-change="refreshChange"
          @size-change="sizeChange"
          @current-change="currentChange"
          @selection-change="selectionChange">
        <template slot="grouplist" slot-scope="scope">
                    <span
                        v-for="(grouplist,index) in scope.row.group"
                        :key="index">
                         <el-tag>{{ grouplist.groupName }} </el-tag>
                    </span>
          <span v-if="scope.row.group === null">未设置</span>
        </template>
        <template v-if="scope.row.qrcode" slot="code" slot-scope="scope">
                    <span
                        v-for="(code,index) in scope.row.qrcode"
                        :key="index">
                         <el-tag>{{ code }} </el-tag>
                    </span>
          <span v-if="scope.row.qrcode.length == 0">未设置</span>
        </template>
        <template slot="state" slot-scope="scope">
          <el-tag v-if="scope.row.state === '0'" type="success">{{ scope.label }}</el-tag>
          <el-tag v-else-if="scope.row.state === '1'" type="danger">{{ scope.label }}</el-tag>
          <el-tag v-else-if="scope.row.state === null" type="info">未设置</el-tag>
        </template>
        <template slot="menu" slot-scope="scope">
          <el-button
              class="filter-item"
              icon="el-icon-edit"
              size="mini"
              type="primary"
              @click="controlHandle(scope.row)">分配
          </el-button>
          <el-button
              class="filter-item"
              icon="el-icon-delete"
              size="mini"
              type="danger"
              @click="deleteHandle(scope.row)">清除
          </el-button>
        </template>
        <!--        <template slot="menuLeft">-->
        <!--          <el-button-->
        <!--              class="filter-item"-->
        <!--              icon="el-icon-plus"-->
        <!--              size="small"-->
        <!--              type="primary"-->
        <!--              @click="batchAddHandle()">批量分配门禁组-->
        <!--          </el-button>-->
        <!--        </template>-->
        <!--        <template slot="menuLeft">-->
        <!--          <el-button-->
        <!--              class="filter-item"-->
        <!--              icon="el-icon-delete"-->
        <!--              size="small"-->
        <!--              type="danger"-->
        <!--              @click="batchDelHandle()">批量清除门禁组-->
        <!--          </el-button>-->
        <!--        </template>-->
      </avue-crud>
      <!--      单个门禁组分配弹窗-->
      <el-dialog
          :visible.sync="dialogEditVisible"
          center
          title="门禁组分配"
          width="45%" @close="dictItemVisible">
        <el-form>
          <el-form-item class="weight">
            <span>当前学生：{{ currentrow.deptParentName }} {{ currentrow.sysDeptName }}&nbsp;{{ currentrow.personName }}&nbsp;学号：{{
                currentrow.number
              }}</span>
          </el-form-item>
          <el-form-item>
            <h4>当前可通行门禁组</h4>
            <el-button v-if="curgroups === null" type="info">未设置</el-button>
            <el-button v-for="(item,index) in curgroups" v-else :key="item.groupName" v-model="item.groupName"
                       type="primary">{{ item.groupName }}
            </el-button>
          </el-form-item>
          <!--          <el-col :span="24">-->
          <avue-form v-model="allgroup" :option="option" placeholder="请选择内容"></avue-form>
          <!--          </el-col>-->
        </el-form>
        <div slot="footer" :span="24">
          <el-button class="filter-item" size="small" type="primary" @click="handleUpdate()">保存分配</el-button>
        </div>
      </el-dialog>

      <!--      单个门禁组清除弹窗-->
      <el-dialog
          :visible.sync="dialogDelVisible"
          center
          title="清除门禁组"
          width="45%" @close="dictDelVisible">
        <el-form>
          <el-form-item class="weight">
            <span>当前学生：{{ currentrow.deptParentName }}{{ currentrow.sysDeptName }}&nbsp;{{ currentrow.personName }}&nbsp;学号：{{
                currentrow.number
              }}</span>
          </el-form-item>
          <el-form-item>
            <h4>当前可通行门禁组</h4>
            <el-button v-if="curgroups === null" type="info">未设置</el-button>
            <el-button v-for="(item,index) in curgroups" v-else :key="item.groupName" v-model="item.groupName"
                       type="primary">{{ item.groupName }}
            </el-button>
          </el-form-item>
        </el-form>
        <div slot="footer" :span="24">
          <el-button class="filter-item" size="small" type="danger" @click="handleDel()">清除门禁组</el-button>
          <el-button class="filter-item" size="small" @click="dictDelVisible()">取消</el-button>
        </div>
      </el-dialog>

      <!--      批量门禁组分配弹窗-->
      <el-dialog
          :visible.sync="dialogbetchAddVisible"
          center
          title="批量门禁组分配"
          width="45%" @close="dictItemVisible">
        <el-form>
          <el-form-item>
            <span>当前筛选人数：{{ chooseList.length }}人</span>
          </el-form-item>
          <!--          <el-col :span="24">-->
          <avue-form v-model="allgroup" :option="option" placeholder="请选择内容"></avue-form>
          <!--          </el-col>-->
        </el-form>
        <div slot="footer" :span="24">
          <el-button class="filter-item" size="small" @click="dictItemVisible()">取消</el-button>
          <el-button class="filter-item" size="small" type="primary" @click="batchSaveHandle()">保存分配</el-button>
        </div>
      </el-dialog>

    </basic-container>
  </div>
</template>

<script>
import {mapGetters} from "vuex";
import {batchdelIdsObj, batchdoorgroupObj, deldoorgroupObj, doorgroupObj} from "@/api/pass/s-doorgroup";
import {qrcode} from '@/api/people/student'
import Vue from "vue";
import {GROUP_SEX, PASS_DETAILS} from '@/const/Dict'
import {PERSON_OPERA} from "@/const/personDict";

export default {
  name: "c-doorgroup",
  data() {
    return {
      dialogEditVisible: false,      //单个分配弹窗
      dialogDelVisible: false,       //单个删除弹窗\
      dialogbetchAddVisible: false,
      dialogbetchDelVisible: false,
      tableData: [],
      searchForm: {},
      tableLoading: false,
      // tableOption: tableOption,
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10 // 每页显示多少条
      },
      //单个分配
      // groupNames: [],
      curgroups: [],
      currentrow: {},
      groupid: '',
      chooseList: [],
      allgroup: {},
      option: {
        submitBtn: false,
        emptyBtn: false,
        column: [{
          prop: 'accessControlIds',
          props: {
            label: 'groupName',
            value: 'id'
          },
          dicUrl: '/campus/accesscontrolgroup/selectAll',
          dicMethod: 'get',
          multiple: true,
          span: 15,
          type: 'select',
          dataType: 'array',
          placeholder: '请选择可通行门禁',
          label: '可通行门禁',
          clearable: false,
        }]
      },
      tableOption: {
        border: true,
        index: true,
        indexLabel: '序号',
        stripe: true,
        menuAlign: 'center',
        menuWidth: 180,
        menuType: 'button',
        align: 'center',
        emptyBtnText: '重置', //清空按钮文案
        refreshBtn: true,
        showClomnuBtn: false,
        searchSize: 'mini',
        searchMenuSpan: 6,
        // searchLabelWidth: 80,
        // searchSpan: 4,
        labelWidth: "20%",
        addBtn: false,
        editBtn: false,
        delBtn: false,
        viewBtn: false,
        // selection: true,
        reserveSelection: true,
        props: {
          label: 'label',
          value: 'value'
        },
        column: [
          {
            label: '人员id',
            prop: 'id',
            hide: true,
          },
          {
            label: '姓名',
            prop: 'personName',
            type: 'input',
            search: true,
          }, {
            label: '学号',
            prop: 'number',
            dicData: PASS_DETAILS,
          }, {
            label: '性别',
            prop: 'sex',
            type: 'select',
            search: true,
            dicData: GROUP_SEX,
            // searchClearable: false,
            change: (value) => {
              this.searchForm.sex = value.value
              this.getList(this.page, this.searchForm)
            },
          }, {
            label: '年级',
            prop: 'deptParentName',
            dicData: PASS_DETAILS,
          },
          {
            label: '年级',
            prop: 'deptId',
            search: true,
            type: 'select',
            hide: true,
            // searchClearable: false,
            defaultExpandAll: true,
            dicUrl: '/admin/dept/PermissionTree',
            cascaderItem: ['deptName'],
            dicFormatter: (res) => {
              return res.data[0].children[0].children[0].children;//返回字典的层级结构
            },
            dicMethod: 'get',
            props: {
              label: 'name',
              value: 'id'
            },
            change: (value) => {
              this.searchForm.deptId = value.value
              this.getList(this.page, this.searchForm)
            },
          },
          {
            label: '班级',
            prop: 'sysDeptName',
            dicData: PASS_DETAILS,
          },
          {
            label: '班级',
            prop: 'deptName',
            search: true,
            filter: false,
            type: 'select',
            hide: true,
            // searchClearable: false,
            defaultExpandAll: true,
            dicUrl: '/campus/sysdept/detpTree/{{key}}/1,2,3',
            dicFormatter: (res) => {
              return res.data[0].children;//返回字典的层级结构
            },
            dicMethod: 'get',
            props: {
              label: 'name',
              value: 'deptId',
            },
            change: (value) => {
              this.searchForm.deptId = value.value
              this.getList(this.page, this.searchForm)
            },
          },
          // {
          //   label: '学生属性',
          //   prop: 'identityKey',
          //   search: true,
          //   type: 'select',
          //   dicUrl: '/campus/identity/selectAll?groupNum=2',
          //   dicMethod: 'get',
          //   props: {
          //     label: 'name',
          //     value: 'id'
          //   },
          //   change: (value) => {
          //     this.searchForm.identityKey = value.value
          //     this.getList(this.page, this.searchForm)
          //   },
          // }, {
          //   label: '楼栋',
          //   prop: 'buildingName',
          //   dicData: PASS_DETAILS,
          // }, {
          //   label: '楼栋',
          //   prop: 'buildingId',
          //   hide: true,
          //   search: true,
          //   type: 'select',
          //   dicUrl: '/campus/building/selectAll',
          //   dicMethod: 'get',
          //   // searchClearable: false,
          //   props: {
          //     label: 'buildingName',
          //     value: 'buildingId'
          //   },
          //   change: (value) => {
          //     this.searchForm.buildingId = value.value
          //     this.getList(this.page, this.searchForm)
          //   },
          // }, {
          //   label: '宿舍号',
          //   prop: 'dormNumber',
          //   dicData: PASS_DETAILS,
          //   search: true,
          //   type: 'input',
          // },
          // {
          //   label: '手机号',
          //   prop: 'phone',
          // },
          {
            label: '可通行门禁',
            prop: 'grouplist',
            slot: true,
          },{
            label: '卡号',
            prop: 'code',
            slot: true
          }, {
            width: 150,
            label: '人员修改时间',
            prop: 'updateTime',
            type: 'datetime',
            format: 'yyyy-MM-dd HH:mm',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            addDisplay: false,
            editDisplay: false,
          }, {
            width: 100,
            label: '修改操作人',
            prop: 'operator',
            dicData: PERSON_OPERA,
          },
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['permissions']),
    permissionList() {
      return {
        delBtn: this.vaildData(this.permissions.sys_time_del, false),
      }
    }
  },
  methods: {
    getList(page, params) {
      this.tableLoading = true
      doorgroupObj(Object.assign({
        current: page.currentPage,
        size: page.pageSize,
        groupNum: 2
      }, params, this.searchForm)).then(response => {
        this.tableData = response.data.data.records
        this.page.total = response.data.data.total
        this.tableData.map(item => {
          qrcode(item.id).then(res => {
            if (res.data.code === 0) {
              this.$set(item, 'qrcode',)
              item.qrcode = res.data.data
            }
          })
        })
        this.tableLoading = false
      })
    },
    // 单个学生门禁组分配
    controlHandle(row) {
      this.dialogEditVisible = true
      this.currentrow = row
      //当前所选门禁
      this.curgroups = row.group
      console.log(this.curgroups)
      // 查询所有的分配方案展示供分配
      if (row.group !== null) {
        this.allgroup.accessControlIds = row.group.map(x => {
          return x.id
        })
      }
    },
    // 保存单个时间方案分配
    handleUpdate: function (row, index, done) {
      // debugger
      // let param = {
      //   personId: this.currentrow.id,
      //   accessGroupIds: this.allgroup.accessControlIds
      // }
      // console.log(this.allgroup.accessControlIds)
      let grouparr = this.allgroup.accessControlIds
      if (grouparr.length === 0) {
        this.$message.warning('所选门禁组不能为空')
        return
      }
      let arr = []
      for (let i in grouparr) {
        var j = {}
        j.accessGroupId = grouparr[i]
        j.personId = this.currentrow.id
        arr.push(j)
      }
      console.log(arr)
      batchdoorgroupObj(arr).then(res => {
        if (res.data.code === 0) {
          this.tableLoading = false
          this.$message.success('分配成功')
        } else {
          this.tableLoading = false
          this.$message.error('分配失败')
        }
        // done()
        this.dialogEditVisible = false
        this.getList(this.page)
      })
    },
    //关闭单个分配弹窗
    dictItemVisible: function (val) {
      this.dialogEditVisible = false
      this.dialogbetchAddVisible = false
      for (let key of Object.keys(this.allgroup)) {
        Vue.delete(this.allgroup, key);
      }
      this.$refs.crud.toggleSelection(val);
    },
    //清楚单个方案分配弹窗
    deleteHandle(row) {
      this.dialogDelVisible = true
      this.currentrow = row
      this.curgroups = row.group
    },
    //关闭单个清除门禁组弹窗
    dictDelVisible: function () {
      this.dialogDelVisible = false
    },
    // 清除单个门禁组
    handleDel: function (row, index) {
      deldoorgroupObj(this.currentrow.id).then(res => {
        if (res.data.code === 0) {
          this.$message.success('清除成功')
        } else {
          this.$message.error('清除失败')
        }
        this.dialogEditVisible = false
        this.dialogDelVisible = false
        this.getList(this.page)
      })
    },
    // 表格的多选方法
    selectionChange(list) {
      // this.$message.success('选中的数据'+ JSON.stringify(list));
      this.chooseList = list
      // console.log(this.chooseList)
    },
    //批量分配门禁组
    //获取所有可选门禁
    batchAddHandle: function () {
      this.dialogbetchAddVisible = true
    },
    //进行批量分配操作
    batchSaveHandle: function (val) {
      // if(this.searchForm !== null){
      //   console.log(this.searchForm)
      //   let selectList= this.tableData
      //   selectList.forEach((value, index) => {
      //     value['accessGroupIds'] = this.allgroup.accessControlIds
      //   })
      //   var selectarr = [];
      //   selectList.forEach(function (item) {
      //     selectarr.push({personId: item.id, accessGroupIds: item.accessGroupIds,})
      //   })
      //   console.log(selectarr)
      //   batchdoorgroupObj(selectarr).then(res => {
      //     if (res.data.code === 0) {
      //       this.$message.success('分配成功')
      //     } else {
      //       this.$message.error('分配失败')
      //     }
      //     this.dialogbetchAddVisible = false
      //     this.chooseList.length = 0
      //     console.log(this.chooseList)
      //     this.getList(this.page)
      //     this.$refs.crud.toggleSelection(val);
      //   })
      // }
      // else

      // {

      // this.chooseList.forEach((value, index) => {
      //   value['accessGroupIds'] = this.allgroup.accessControlIds
      // })
      // var arr = [];
      // this.chooseList.forEach(function (item) {
      //   arr.push({personId: item.id, accessGroupIds: item.accessGroupIds,})
      // })
      // console.log(arr)
      // 2021/4/6  批量分配门禁组入参改成和单个分配一样的格式
      let grouparr = this.allgroup.accessControlIds
      let arr = []
      for (let i in grouparr) {
        // j.personId = this.currentrow.id
        this.chooseList.forEach(function (item) {
          let j = {}
          j.accessGroupId = grouparr[i]
          j.personId = item.id
          // console.log(j)
          arr.push(j)
        })
      }
      batchdoorgroupObj(arr).then(res => {
        if (res.data.code === 0) {
          this.$message.success('分配成功')
        } else {
          this.$message.error('分配失败')
        }
        this.dialogbetchAddVisible = false
        this.chooseList.length = 0
        console.log(this.chooseList)
        this.getList(this.page)
        this.$refs.crud.toggleSelection(val);
      })
      // }
    },
    //批量清除门禁组
    batchDelHandle: function (val) {
      let ids = this.chooseList.map(x => {
        return x.id
      })

      if (ids.length === 0) {
        this.$message.error('请选择要清除门禁的人员')
      } else {
        batchdelIdsObj(ids).then(res => {
          if (res.data.code === 0) {
            this.$message.success('清除成功')
          } else {
            this.$message.error('清除失败')
          }
          this.dialogbetchDelVisible = false
          this.getList(this.page)
          this.$refs.crud.toggleSelection(val);
        })
      }
    },

    searchChange(form, done) {
      if (form.deptName !== undefined) {
        form.deptId = form.deptName
      }
      this.searchForm = form
      this.page.currentPage = 1
      this.getList(this.page, form)
      done()
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize
    },
    currentChange(current) {
      this.page.currentPage = current
    },
    refreshChange() {
      this.getList(this.page)
    },
    searchReset() {
      this.searchForm = {};
      this.getList(this.page)
    }
  }
}
</script>

<style scoped>
/deep/.avue-crud__menu{
  display: none;
}
/deep/.el-form-item__label{
  text-align: left;
}
/deep/.avue-form__row{
  padding-left: 0 !important;
  padding-right: 36px!important;
}
/deep/.avue-form__menu--center{
  text-align: left;
}
/deep/.avue-form__menu--center .el-button{
  margin: 0 20px 0 0;
}
/deep/.el-dialog--center .el-dialog__body{
  padding: 0 25px 30px;
}
.weight{
  font-weight: bold;
  margin-bottom: 0;
}
h4{
  padding: 0;
  margin: 5px 0;
}
</style>